import 'dart:async';
import 'dart:io';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
import '../../base/MyScaffold.dart';
import '../../res.dart';
import '../../sqflite/DBUtil.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:open_file/open_file.dart';

import '../../config/Constant.dart';
import '../../model/Bus.dart';
import '../../model/PDFFile.dart';
import '../../model/Process.dart';
import '../../sqflite/CreateTableSqls.dart';
import '../../utils/EventBus/EventBus.dart';
import '../../utils/color/ColorUtils.dart';
import '../../utils/userbloc/user_bloc.dart';
import '../convert/PDFView.dart';
import '../subscribe/Subscribe.dart';

class Processing extends StatefulWidget {
  const Processing({Key? key}) : super(key: key);

  @override
  State<Processing> createState() => _ProcessingState();
}

class _ProcessingState extends State<Processing> {
  List<Process> list = [];
  late DBUtil dbUtil;
  StreamSubscription? subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dbUtil = DBUtil();
    subscription = EventBusUtil.addListener<Bus>((event) async {
      if (event.label == Constant.CONVERT_MSG) {
        getData();
      }
    });
    getData();
  }

  getData() async {
    list.clear();
    await dbUtil.open();
    await dbUtil.query(processing, orderBy: "id desc").then((value) {
      for (Map<String, dynamic> map in value) {
        list.add(Process(
            id: map["id"],
            name: map["name"],
            type: map["type"],
            path: map["path"],
            img: map["img"],
            value: map["value"],
            error: map["error"],
            state: map["state"],
            label: map["state"]));
      }
      setState(() {});
    });
  }

  delete(int id) async {
    await dbUtil.open();
    await dbUtil.deleteByHelper(processing, whereStr: 'id=?', whereArgs: [id]);
  }

  getState(int state) {
    if (state == 0) {
      return "processing".tr;
    } else if (state == 1) {
      return "success".tr;
    } else {
      return "fail".tr;
    }
  }

  @override
  void dispose() {
    // 页面销毁时一定要 cancel 掉定时器，不然会一直执行
    dbUtil.close();
    EventBusUtil.removeListener(subscription!);
    super.dispose();
  }

  String formatFileSize(int size) {
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    double value = size.toDouble();
    int unitIndex = 0;
    while (value >= 1024 && unitIndex < units.length - 1) {
      value /= 1024;
      unitIndex++;
    }

    return '${(value * 100).round() / 100} ${units[unitIndex]}';
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      title: "processing_records".tr,
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemBuilder: (c, index) {
                Process process = list[index];
                print(process.toString());
                List<String> splitString =
                    process.path.split("/"); // 以逗号和空格为分隔符拆分字符串
                String substring = splitString[6];
                return InkWell(
                  onTap: () {
                    if (process.state == 1) {
                      int length = process.path.length;
                      var type = process.path.substring(length - 3, length);
                      if (type == "pdf") {
                        PDFFile file = PDFFile(
                            name: process.name,
                            path: process.path,
                            time: formatDate(DateTime.now(),
                                [yyyy, "/", mm, "/", dd, "  ", HH, ":", nn]),
                            size: formatFileSize(
                                File(process.path).lengthSync()));
                        Get.to(PView(
                          pdfFile: file,
                        ));
                      } else {
                        if (process.label == 4) {
                          final files = <XFile>[];
                          files.add(XFile(process.path));
                          Share.shareXFiles(files, text: process.path);
                        } else {
                          OpenFile.open(process.path,
                              type: Constant.android[process.type]);
                        }
                      }
                    }
                  },
                  onLongPress: () {
                    delete(process.id);
                    list.removeAt(index);
                    setState(() {});
                  },
                  child: Container(
                    height: 80,
                    margin: const EdgeInsets.symmetric(horizontal: 16),
                    child: Row(
                      children: [
                        MyLocalImage(
                          process.img,
                          width: 40,
                          height: 40,
                          margin: const EdgeInsets.only(right: 12),
                        ),
                        Expanded(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              TextView(process.state == 0 || process.state == 2
                                  ? process.name
                                  : substring),
                              Row(
                                children: [
                                  TextView(
                                    "${list[index].type}  " +
                                        getState(list[index].state),
                                    style: TextStyle(
                                        color: rgba(150, 151, 153, 1),
                                        fontSize: 10),
                                    margin: const EdgeInsets.only(top: 8),
                                  ),
                                  const Spacer(),
                                  Visibility(
                                    visible:
                                        list[index].state != 1 ? true : false,
                                    child: TextView(
                                      list[index].state == 2
                                          ? list[index].error
                                          : "${list[index].value.toInt()}%",
                                      style: TextStyle(
                                          color: list[index].state == 2
                                              ? rgba(255, 0, 14, 1)
                                              : rgba(150, 151, 153, 1),
                                          fontSize: 10),
                                      margin: const EdgeInsets.only(top: 8),
                                    ),
                                  ),
                                ],
                              ),
                              Visibility(
                                visible: list[index].state != 0 ? false : true,
                                child: Padding(
                                  padding: const EdgeInsets.only(top: 12),
                                  child: LinearProgressIndicator(
                                    value: list[index].value.toInt() * 0.01,
                                    backgroundColor: rgba(247, 247, 247, 1),
                                    borderRadius: BorderRadius.circular(2),
                                    valueColor:
                                        const AlwaysStoppedAnimation<Color>(
                                            Colors.blue),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        // Container(
                        //   width: 30,
                        //   height: 30,
                        //   margin: const EdgeInsets.only(left: 10),
                        //   child: Visibility(
                        //     visible: list[index].state == 2 ? true : false,
                        //     child: const MyLocalImage(
                        //       Res.sys_icon_file_retry,
                        //       width: 16,
                        //       height: 16,
                        //     ),
                        //   ),
                        // ),
                      ],
                    ),
                  ),
                );
              },
              itemCount: list.length,
            ),
          ),
          Visibility(
            visible: UserBlocTool.getUser()?.is_vip == "1" ? false : true,
            child: Container(
              height: 60,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              margin: const EdgeInsets.symmetric(vertical: 24, horizontal: 16),
              decoration: BoxDecoration(
                  gradient: LinearGradient(colors: [
                    rgba(221, 245, 253, 1),
                    rgba(204, 206, 251, 1),
                  ]),
                  borderRadius: BorderRadius.circular(6)),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const MyLocalImage(
                    Res.banner_icon_crow,
                    width: 32,
                    height: 32,
                  ),
                  Expanded(
                    child: Container(
                      margin: const EdgeInsets.only(left: 12),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TextView(
                            "to_pro".tr,
                            style: TextStyle(
                                color: ColorUtils.text,
                                fontSize: 14,
                                fontWeight: FontWeight.bold),
                          ),
                          TextView("unlock_unlimited".tr,
                              margin: const EdgeInsets.only(top: 4),
                              style: TextStyle(
                                  color: ColorUtils.text_, fontSize: 12)),
                        ],
                      ),
                    ),
                  ),
                  MyLocalImage(
                    Res.nav_icon_getpro,
                    width: 75,
                    height: 32,
                    onclick: () {
                      Get.to(const Subscribe());
                    },
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
